﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace FourKill.Engine
{
    public class GroundPolygon : IPaintable
    {
        private const int SECTION_LENGTH = 20;
        private readonly List<Coordinates3D> _path;
        private Brush _brush;

        public GroundPolygon(List<Coordinates3D> path, Color c)
        {
            _brush = new SolidBrush(c);
            _path = path;
        }

        public void Paint(IPaintableContext context)
        {
            var g = context.BackLayer;
            try
            {
                bool isDrawable = false;
                List<Point> pathPoints = new List<Point>();
                List<IPlacement> relativePolygon = new List<IPlacement>();

                for (int i = 0; i < _path.Count; i++)
                {
                    ICoordinates3D c = _path[i];

                    IPlacement relativePlacement = new Placement();
                    Utility.FindRelativeLocation3D(context.Camera, c, ref relativePlacement);
                    relativePolygon.Add(relativePlacement);
                }

                if (Utility.ClipPolygonOnYAxis(relativePolygon, context.ViewPort.DistanceToView))
                {
                    isDrawable = true;
                    for (int i = 0; i < relativePolygon.Count; i++)
                    {
                        IPlacement c = relativePolygon[i];

                        IPointViewLocation pvl = new PointViewLocation { Placement = c };
                        Utility.CalculatePointViewLocation(ref pvl, context.Camera, context.ViewPort, c, true);

                        if (pvl.Placement.X < context.ViewPort.DistanceToView)
                        {
                            isDrawable = false;
                            break;
                        }

                        pathPoints.Add(pvl.Point);
                    }
                }
                if (isDrawable) g.FillPolygon(_brush, pathPoints.ToArray());
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("***********************************");
                System.Diagnostics.Debug.WriteLine(ex.Message + "\r\n" + ex.StackTrace);
                System.Diagnostics.Debugger.Break();
            }
        }
    }
}
